import React, { Component } from 'react';
import { Button, Form, Input, Select, message } from 'antd';
import { messages, removeArrayItemByKey } from 'share/common';
import CompactInput from 'components/compact-input';
import Muuri from 'muuri';
import 'styles/data-center/report-management/single-field-comp.scss';
const FormItem = Form.Item;
import InputLanguage from 'components/template/input-language';

class SingleFieldComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: []
    };
    this.key = 1;
    this.grid = null;
    this.index = 1000000;
  }

  componentDidMount() {
    const { onRef, value } = this.props;
    onRef && onRef(this);
    this.setValues(this.props.value)
  }

  initMuuri = (List) => {
    if (this.grid) {
      let data = this.getMuuriItemKeyArray(this.grid);
      List.forEach((item)=>{
        let target = data.find(id => item.id === id);
        if (target === undefined) {
          let items = this.grid.add(document.getElementById(item.id), { index: -1, active: false });
          this.grid.show(items);
        }
      })
      return
    }
    this.grid = new Muuri('.field-container');
  }

  getMuuriItemKeyArray = (grid) => {
    let itemIds = grid.getItems()
      .map((item) => {
        return item.getElement()
          .getAttribute('data-id');
      });
    return itemIds;
  };

  componentWillUnmount() {
    this.grid.destroy();
  }

  componentWillReceiveProps(nextProps) {
    this.setValues(nextProps.value);
  }

  setValues = value => {
    value.forEach((item, index)=>{
      value[index].index = index;
    })
    this.setState({list: value}, ()=>{this.initMuuri(value)})
  }

  onChange = () => {
    const { onChange } = this.props;
    onChange && onChange(this.state.list);
  };

  onNameChange = (value, index) => {
    const { list } = this.state;
    list[index].columnDisplayName = value.columnDisplayName.name;
    list[index].i18n.columnDisplayName = value.columnDisplayName.i18n;
    this.setState({list}, this.onChange)
  }

  onTypeChange = (value, index) => {
    const { list } = this.state;
    list[index].dataType = value.dataType;
    this.setState({list}, this.onChange)
  }

  addSingleField = () => {
    const { list } = this.state;
    if (list && list.length < 100) {
      list.push({uniqueId: this.index, i18n: {columnDisplayName: []}, columnDisplayName: undefined, dataType: undefined});
      this.index++;
      this.setState({list}, ()=>{
        this.onChange();
        let items = this.grid.add(document.getElementById(list[list.length - 1].uniqueId), { index: -1, active: false });
        this.grid.show(items);
      });
    } else {
      message.warn(messages('basic-10.key221')/*最多添加100个字段*/);
    }
  }

  deleteSingleItem = (e, item) => {
    e.preventDefault();
    let list = removeArrayItemByKey(this.state.list, item, 'index');
    let deleteItem = this.grid.getItems()
      .filter((filterItem) => {
        return filterItem.getElement().getAttribute('data-id') === (item.id || item.uniqueId).toString()
      });
    this.grid.remove(deleteItem, { removeElements: false });
    this.setState({list}, this.onChange)
  }

  validateFields = () => {
    const { list } = this.state;
    let result = true;
    list.every((item, index)=>{
      if (!item.columnDisplayName) {
        message.warn(`排序为【${index+1}】的字段，未填写字段名`);
        result = false;
        return false
      }
      if (!item.dataType) {
        message.warn(`排序为【${index+1}】的字段，未选择字段类型`);
        result = false;
        return false
      }
      return true
    })
    return result
  }

  render() {
    const { list } = this.state;
    return (
      <div className='single-field-component'>
        <FormItem required label={messages('basic-10.key222')/*数据源字段*/}>
          <Button type={'primary'} onClick={this.addSingleField}>{messages('basic-10.key223')/*新增字段*/}</Button>
        </FormItem>
        <FormItem label={messages('basic-10.key224')/*字段排序*/}>
          <div style={{display: 'flex', width: '66%'}}>
            <div style={{width: '60%'}}>{messages('basic-10.key225')/*字段名*/}</div><div>{messages('basic-10.key226')/*字段类型*/}</div>
          </div>
        </FormItem>
        <div className="field-container">
          {list.map((item, index)=>
            <div className={'single-field-item'} key={item.id || item.uniqueId} data-id={item.id || item.uniqueId} id={item.id || item.uniqueId}>
              <FormItem label={index + 1} key={item.id || item.uniqueId}>
                <div className='compact-and-delete-btn'>
                  <CompactInput className={'custom-report-compact'}>
                    <InputLanguage
                      value={{ name: item.columnDisplayName, i18n: item.i18n ? item.i18n.columnDisplayName : [] }}
                      placeholder={messages('common.max.characters.length',{arg1: 10})/*最多输入{arg1}个字符*/}
                      maxLength={10}
                      onChange={e => this.onNameChange({ columnDisplayName: e, dataType: item.dataType, id: item.id, uniqueId: item.uniqueId }, index)}
                    />
                    <Select
                      allowClear
                      value={item.dataType}
                      placeholder={messages('common.select')/*请选择*/}
                      onChange={newValue => this.onTypeChange({ dataType: newValue, columnDisplayName: item.columnDisplayName, id: item.id, uniqueId: item.uniqueId }, index)}
                    >
                      <Select.Option key={'string'}>{messages('basic-10.key228')/*文本*/}</Select.Option>
                      <Select.Option key={'bigdecimal'}>{messages('common.amount')/*金额*/}</Select.Option>
                      <Select.Option key={'number'}>{messages('basic-10.key229')/*数字*/}</Select.Option>
                      <Select.Option key={'date'}>{messages('common.date')/*日期*/}</Select.Option>
                      <Select.Option key={'dateTime'}>{messages('basic-10.key230')/*日期+时间*/}</Select.Option>
                    </Select>
                  </CompactInput>
                  <a className='delete-btn' onClick={(e)=>{this.deleteSingleItem(e, item)}}>{messages('common.delete')/*删除*/}</a>
                </div>
              </FormItem>
            </div>
          )}
        </div>
      </div>
    );
  }
}

SingleFieldComp.propTypes = {};

export default SingleFieldComp;
